package com.edu.chapter09_kotlin.network

import com.edu.chapter09_kotlin.model.MyResponse
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.MediaType.Companion.toMediaType
import java.io.IOException

class OkHttpHelper {
    // 使用伴生对象替代静态成员
    companion object {
        private val client by lazy { OkHttpClient() }
        private val gson by lazy { Gson() }
    }

    // 使用高阶函数替代接口回调
    fun searchGames(num: Int, callback: (Result<MyResponse>) -> Unit) {
        val url = "https://hotfix-service-prod.g.mi.com/quick-game/game/$num".toHttpUrlOrNull()!!
            .newBuilder()
            .build()

        val request = Request.Builder()
            .url(url)
            .header("Content-Type", "application/json")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                try {
                    val body = response.body?.string() ?: throw IOException("Empty response body")
                    val type = object : TypeToken<MyResponse>() {}.type
                    val res = gson.fromJson<MyResponse>(body, type)
                    callback(Result.success(res))
                } catch (e: Exception) {
                    callback(Result.failure(e))
                }
            }

            override fun onFailure(call: Call, e: IOException) {
                callback(Result.failure(e))
            }
        })
    }
}